import Vue from 'vue';

const isServer = typeof window === 'undefined';
let index = 20141223;
const Toast = Vue.extend({
  name: 'ToastMessage',
  data () {
    return {
      messages: []
    };
  },
  methods: {
    open (message) {
      const id = 'toast-id-' + index++;
      this.messages.push({
        message,
        id
      });
      return id;
    },
    close (id) {
      if (!id) return;
      let index = -1;
      for (let i = 0; i < this.messages.length; i++) {
        if (this.messages[i].id === id) {
          index = i;
          break;
        }
      }
      if (index === -1) return;
      this.messages.splice(index, 1);
    }
  },
  // eslint-disable-next-line no-unused-vars
  render (h) {
    return <div>
      <transition-group name="mu-fade-transition">
        {
          this.messages.map(({ id, message }) => {
            return <co-toast key={id}>{message}</co-toast>;
          })
        }
      </transition-group>
    </div>;
  }
});
let toast;
export default function (message, timeout = 2000) {
  if (isServer) return;
  if (!toast) {
    toast = new Toast({
      el: document.createElement('div')
    });
    document.body.appendChild(toast.$el);
  }
  const id = toast.open(message);
  setTimeout(() => {
    toast.close(id);
  }, timeout);
}
